package br.ita.redecasd.mi.auth;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import javax.naming.NamingException;

import br.ita.redecasd.mi.ldap.LDAPManager;

/**
 *
 * @author mi
 */
public class SignValidator {

    public static boolean validateSignature(String username, String userAgent, byte[] signature ) throws FileNotFoundException, CertificateException, IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, NamingException {
        //Lê o certificado do servidor LDAP
    	LDAPManager manager = new LDAPManager();
    	byte[] certBin = manager.getCertificateBin(username);
    	
    	if ( certBin == null )
    		return false;
    	
    	ByteArrayInputStream istream = new ByteArrayInputStream( certBin );
    	CertificateFactory cfactory = CertificateFactory.getInstance( "X.509" );
        Certificate cert = cfactory.generateCertificate( istream );
        istream.close();

        //valida a assinatura
        Signature sig = Signature.getInstance("SHA1withDSA");
        sig.initVerify( cert );
        sig.update( userAgent.getBytes());
        return sig.verify(signature);
        
    }

}
